import React from "react";
import Taro, { eventCenter } from "@tarojs/taro";
import { View, Input, Image, Form } from "@tarojs/components";
import { Button, Cell, Row, Col } from "@nutui/nutui-react-taro";
import { AuthUtil, UserApi } from "../../utils/api";
import "./index.less";

function UserInfo() {
  const [userInfo, setUserInfo] = React.useState({
    avatarUrl: "",
    avatar: { url: "", id: "" },
    nickName: "",
  });
  interface UserInfo {
    avatarUrl: string;
    avatar: { url: string; id: string };
    nickName: string;
  }
  React.useEffect(() => {
    const userInfo: UserInfo = Taro.getStorageSync("userInfo");
    if (userInfo) {
      const avatarUrl = userInfo.avatar?.url || "";
      const nickName = userInfo.nickName || "";
      const avatarId = userInfo.avatar?.id || "";
      setUserInfo({
        avatarUrl,
        nickName,
        avatar: { id: avatarId, url: avatarUrl },
      });
      console.log(userInfo, "userInfo");
    }
  }, []);

  const onChooseAvatar = (e) => {
    console.log(e.detail.avatarUrl, "avatarUrl");
    const avatarUrl = e.detail.avatarUrl;
    if (!avatarUrl) return;
    AuthUtil.uploadFile(avatarUrl).then((res: any) => {
      setUserInfo({ ...userInfo, avatar: { id: res.id, url: res.url } });
    });
  };
  const changenickName = (e: any) => {
    console.log(e, "nickName");
    if (e.detail.value) {
      setUserInfo({ ...userInfo, nickName: e.detail.value });
    } else {
      return;
    }
  };

  //   get user info
  const fetchUserInfo = async () => {
    try {
      const data: any = await UserApi.getCurrentUserInfo();
      // Store updated user info
      if (data) {
        Taro.setStorageSync("userInfo", data);
        // eventCenter.trigger("updateUserInfo", data);
        Taro.showToast({ title: "更新成功", icon: "success" });
        Taro.navigateBack();
      }
    } catch (error) {
      console.error("获取用户信息失败", error);
    } finally {
      Taro.hideLoading();
    }
  };

  const submit = (e) => {
    const nickname = e.detail.value.nickname;
    if (nickname) {
      setUserInfo({ ...userInfo, nickName: e.detail.value.nickname });
    } else {
      return;
    }

    const id = Taro.getStorageSync("userInfo").id;
    const params = {
      ...(userInfo.avatar.id && { avatar: userInfo.avatar.id }),
      ...(nickname && {
        nickName: nickname,
      }),
    };
    Taro.showLoading({
      title: "更新中...",
    });

    UserApi.updateUser(id, params).then((res) => {
      if (res) {
        fetchUserInfo();
      } else {
        Taro.showToast({
          title: "更新失败",
          icon: "none",
        });
        Taro.hideLoading();
      }
    });
  };

  const signOut = () => {
    Taro.clearStorageSync();
    Taro.showToast({ title: "退出登录成功", icon: "success", duration: 1000 });
    eventCenter.trigger("updateUserInfo", {});
    Taro.navigateBack();
  };

  return (
    <View className="user-info">
      <Form onSubmit={submit} onReset={signOut}>
        <Cell className="cell">
          <Row>
            <Col span={6}>
              <View className="label">昵称</View>
            </Col>
            <Col span={18}>
              <Input
                className="user-name"
                type="nickname"
                name="nickname"
                value={userInfo.nickName}
                placeholder="请输入昵称"
              />
            </Col>
          </Row>
        </Cell>
        <Cell className="cell">
          <Row className="cell">
            <Col span={6}>
              <View className="label">头像</View>
            </Col>
            <Col span={18}>
              <View className="info-content__btn-container">
                <Button
                  open-type="chooseAvatar"
                  onChooseAvatar={onChooseAvatar}
                  className="info-content__btn"
                />
                <Image
                  src={userInfo.avatar?.url}
                  className="info-content__avatar"
                />
              </View>
            </Col>
          </Row>
        </Cell>
        <view className="btn-container">
          <Button className="submit-btn" form-type="submit" type="primary">
            保存
          </Button>
          <Button className="submit-btn" type="default" onClick={signOut}>
            退出登录
          </Button>
        </view>
      </Form>
    </View>
  );
}

export default UserInfo;
